//
//  PhotoView.m
//  PhotoProject
//
//  Created by 艾玩科技 on 17/3/22.
//  Copyright © 2017年 随心. All rights reserved.
//


#define imageH 100 // 图片高度
#define imageW 75 // 图片宽度
#define kMaxColumn 3 // 每行显示数量
#define MaxImageCount 9 // 最多显示图片个数
#define deleImageWH 25 // 删除按钮的宽高
#define kAdeleImage @"icon_jia.png" // 删除按钮图片
#define kAddImage @"+.png" // 添加按钮图片
#import "GTMBase64.h"

#import "PhotoView.h"
#import "UPYUNConfig.h"
#import "UpYun.h"
#import "UpYunFormUploader.h"

@implementation PhotoView
{
    
    // 标识被编辑的按钮 -1 为添加新的按钮
    NSInteger editTag;
    UIProgressView *_pv;
}





-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
       _pv  = [[UIProgressView alloc] initWithFrame:CGRectMake(30, self.bottom , KScreenWidth -60, 1)];
        [self.superview addSubview:_pv];
        UIButton *btn = [self createButtonWithImage:kAddImage andSeletor:@selector(addNewBtn:)];
        [self addSubview:btn];
    }
    return self;
}

-(NSMutableArray *)images
{
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}
//添加新的控件
-(void)addNewBtn:(UIButton *)btn
{
    //标识为添加一个新的图片
    if (![self deleClose:btn]) {
        editTag = -1;
//        [self callImagePicker];
        [self imageTouchAction];
    }
    
    
    
}
//修改旧的控件
-(void)changeOld:(UIButton *)btn
{
    //标识为修改（tag为修改标识）
    if (![self deleClose:btn]) {
        editTag = btn.tag;
//        [self callImagePicker];
        
        [self imageTouchAction];
    }
}
//删除“删除按钮”
-(BOOL)deleClose:(UIButton *)btn
{
    if (btn.subviews.count == 2) {
        [[btn.subviews lastObject] removeFromSuperview];
        [self stop:btn];
        return YES;
    }
    return NO;
}
//调用图片选择器
-(void)callImagePicker
{
    UIImagePickerController *pc = [[UIImagePickerController alloc] init];
    pc.allowsEditing = YES;
    pc.delegate =self;
    //：
    [[self viewController] presentViewController:pc animated:YES completion:nil];
    
    
}

//获取View所在的Viewcontroller方法
- (UIViewController *)viewController {
    
    
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
            
            
           
        }
    }
    return nil;
}

//根据图片名称或者图片创建一个新的显示控件
-(UIButton *)createButtonWithImage:(id)imageNameOrImage andSeletor:(SEL)selector
{
    UIImage *addImage = nil;
    
       if ([imageNameOrImage isKindOfClass:[NSString class]]) {
           
           addImage = [UIImage imageNamed:imageNameOrImage];
           
       }
       else if([imageNameOrImage isKindOfClass:[UIImage class]])
           
       {
                   addImage = imageNameOrImage;
           
       }
    //添加图片按钮
       UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       [addBtn setImage:addImage forState:UIControlStateNormal];
       [addBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
       addBtn.tag = self.subviews.count;
    
        // 添加长按手势,用作删除.加号按钮不添加
        if(addBtn.tag != 0)
           {
              UILongPressGestureRecognizer *gester = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
                [addBtn addGestureRecognizer:gester];
               
           }
      return addBtn;
}
//长按添加删除按钮
-(void)longPress:(UIGestureRecognizer *)gester
{
    if (gester.state == UIGestureRecognizerStateBegan)
            {
              UIButton *btn = (UIButton *)gester.view;
          
                UIButton *dele = [UIButton buttonWithType:UIButtonTypeCustom];
                dele.bounds = CGRectMake(0, 0, deleImageWH, deleImageWH);
              [dele setImage:[UIImage imageNamed:kAdeleImage] forState:UIControlStateNormal];
               [dele addTarget:self action:@selector(deletePic:) forControlEvents:UIControlEventTouchUpInside];
                 dele.frame = CGRectMake(btn.frame.size.width - dele.frame.size.width, 0, dele.frame.size.width, dele.frame.size.height);
           
                [btn addSubview:dele];
               [self start : btn];
                
               }
}

// 长按开始抖动
- (void)start : (UIButton *)btn {
      double angle1 = -5.0 / 180.0 * M_PI;
       double angle2 = 5.0 / 180.0 * M_PI;
         CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
        anim.keyPath = @"transform.rotation";
   
       anim.values = @[@(angle1),  @(angle2), @(angle1)];
        anim.duration = 0.25;
        // 动画的重复执行次数
        anim.repeatCount = MAXFLOAT;
   
      // 保持动画执行完毕后的状态
       anim.removedOnCompletion = NO;
      anim.fillMode = kCAFillModeForwards;
    [btn.layer addAnimation:anim forKey:@"shake"];
 
    
}
//停止抖动
-(void)stop:(UIButton *)btn
{
    [btn.layer removeAnimationForKey:@"shake"];
}

// 删除图片
- (void)deletePic : (UIButton *)btn
 {
       [self.images removeObject:[(UIButton *)btn.superview imageForState:UIControlStateNormal]];
         [btn.superview removeFromSuperview];
     
     if ([[self.subviews lastObject] isHidden]) {
         
         [[self.subviews lastObject] setHidden:NO];
         
     }
    
    
     }
// 对所有子控件进行布局
- (void)layoutSubviews
 {
       [super layoutSubviews];
       NSInteger count = self.subviews.count;

     CGFloat btnW =  ([UIScreen mainScreen].bounds.size.width -40)/3.0f;
     CGFloat btnH =  ([UIScreen mainScreen].bounds.size.width -40)/3.0f;
       int maxColumn = kMaxColumn > self.frame.size.width / imageW ? self.frame.size.width / imageW : kMaxColumn;
        CGFloat marginX = (self.frame.size.width - maxColumn * btnW) / (count + 1);
        CGFloat marginY = marginX;
         for (int i = 0; i < count; i++) {
                 UIButton *btn = self.subviews[i];
                 CGFloat btnX = (i % maxColumn) * (marginX + btnW) + marginX;
                 CGFloat btnY = (i / maxColumn) * (marginY + btnH) + marginY;
                 btn.frame = CGRectMake(btnX,  btnY, btnW, btnH);
             }
    
     }

 #pragma mark - UIImagePickerController 代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
 {
     
    
     
     UIImage *newPhoto ;
     
     if ([info objectForKey:UIImagePickerControllerOriginalImage]) {
         //相册选取
         newPhoto = [info objectForKey:UIImagePickerControllerOriginalImage];
     }
     else if ([info objectForKey:UIImagePickerControllerEditedImage])
     {
         //相机拍摄
         newPhoto =[info objectForKey:UIImagePickerControllerEditedImage];
     }

     
     [self upImageWithImage:newPhoto fileUrl:nil];
     
       if (editTag == -1)
       {
               // 创建一个新的控件
               UIButton *btn = [self createButtonWithImage:newPhoto andSeletor:@selector(changeOld:)];
               [self insertSubview:btn atIndex:self.subviews.count - 1];
//               [self.images addObject:newPhoto];
               if (self.subviews.count - 1 == MaxImageCount) {
                   
                   [[self.subviews lastObject] setHidden:YES];
          
                   
               }
          }
          else
           {
                    // 根据tag修改需要编辑的控件
                  UIButton *btn = (UIButton *)[self viewWithTag:editTag];
//                 NSInteger index = [self.images indexOfObject:[btn imageForState:UIControlStateNormal]];
//                 [self.images removeObjectAtIndex:index];
                 [btn setImage:newPhoto forState:UIControlStateNormal];
//                [self.images insertObject:newPhoto atIndex:index];
               
               
                 }
     
     
     
        // 退出图片选择控制器
        [picker dismissViewControllerAnimated:YES completion:nil];
     
 }
#pragma mark 上传图片
- (void)upImageWithImage:(UIImage *)imagen fileUrl:(NSURL *)fileUrl{
    
    UIImage * image = [self imageCompressWithSimple:imagen scale:1];
    
    //    NSURL *assetURL = fileUrl;
    //获取文件格式(以防图片过大模糊或者压缩)
    //    NSString *fileType = [assetURL pathExtension];
    NSData *data=UIImageJPEGRepresentation(image, 1.0);
    if (data.length>8*1024*1024) {//8M以及以上
        image = [ChineseToEn imageCompressForWidth:image targetWidth:1000.f];
        data=UIImageJPEGRepresentation(image, 0.1);
    }else if (data.length>1024*1024) {//1M-8M
        data=UIImageJPEGRepresentation(image, 0.1);
    }else if (data.length>512*1024) {//0.5M-1M
        data=UIImageJPEGRepresentation(image, 0.5);
    }else if (data.length>200*1024) {//0.25M-0.5M
        data=UIImageJPEGRepresentation(image, 0.9);
    }

//
    
    

    UpYunFormUploader *up = [[UpYunFormUploader alloc] init];
    //上传空间名
    NSString *bucketName = @"feima-img";
    
    [up uploadWithBucketName:bucketName
                    operator:@"root"
                    password:@"feima666"
                    fileData:data
                    fileName:nil
                     saveKey:@"{year}/{mon}/{day}/upload_{random32}{.suffix}.jpg"
             otherParameters:nil
                     success:^(NSHTTPURLResponse *response,
                               NSDictionary *responseBody) {
                         //主线程刷新ui
                         dispatch_async(dispatch_get_main_queue(), ^{
                             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"上传成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                             [alert show];
                             
                             
                             [[NSNotificationCenter defaultCenter] postNotificationName:@"alertSucess" object:nil userInfo:nil];
                             NSString *totalUrlStr = [NSString stringWithFormat:@"%@/%@",img_urlString,[responseBody objectForKey:@"url"]];
                             
                             [self.images addObject:totalUrlStr];
                         });
                     }
                     failure:^(NSError *error,
                               NSHTTPURLResponse *response,
                               NSDictionary *responseBody) {
                   
                         
                         
                         //主线程刷新ui
                         dispatch_async(dispatch_get_main_queue(), ^(){
                             NSString *message = [responseBody objectForKey:@"message"];
                             if (!message) {
                                 message = [NSString stringWithFormat:@"%@", error.localizedDescription];
                             }
                  
                             
                             
                             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"上传失败，重新点击图片上传！" message:message  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                             [alert show];
                             
                             
                         });
                     }
     
                    progress:^(int64_t completedBytesCount,
                               int64_t totalBytesCount) {
//                        NSString *progress = [NSString stringWithFormat:@"%lld / %lld", completedBytesCount, totalBytesCount];
                        NSString *progress_rate = [NSString stringWithFormat:@"%.1f", (float)completedBytesCount / totalBytesCount];
                        
                        //主线程刷新ui
                        dispatch_async(dispatch_get_main_queue(), ^(){
                            //                            [self.uploadBtn setTitle:progress_rate forState:UIControlStateNormal];
                            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                            [dict  setObject:progress_rate forKey:@"rate"];
                            
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"upimgsRate" object:nil userInfo:dict];
                            
                        });
                    }];
    

    
    
}


- (NSString * )getSaveKeyWith:(NSString *)suffix {
    //设置存储路径：生成 saveKey
    
    //方式1 本地生产绝对值 saveKey
    return [NSString stringWithFormat:@"/%@.%@", [self getDateString], suffix];
    
    //方式2 由服务器根据格式生成 saveKey
    //return [NSString stringWithFormat:@"/{year}/{mon}/{filename}{.suffix}"];
    
    //更多方式 参阅 http://docs.upyun.com/api/form_api/#_5
}

- (NSString *)getDateString {
    NSDate *curDate = [NSDate date];//获取当前日期
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy/MM/dd"];//这里去掉 具体时间 保留日期
    NSString * curTime = [formater stringFromDate:curDate];
    curTime = [NSString stringWithFormat:@"%@/%.0f", curTime, [curDate timeIntervalSince1970]];
    return curTime;
}
- (UIImage*)imageCompressWithSimple:(UIImage*)image scale:(float)scale
{
    CGSize size = image.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGFloat scaledWidth = width * scale;
    CGFloat scaledHeight = height * scale;
    UIGraphicsBeginImageContext(size); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//点击添加按钮之后弹出的提示框
- (void)imageTouchAction
{
    
    UIActionSheet *actionS = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相机" otherButtonTitles:@"相册", nil];
    
    [actionS showInView:self];
    
}

#pragma mark actionSheetDelegate 根据提示框按钮的index来判断调用相机还是相册
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        //相机拍照
        [self photoPai];
    }else if(buttonIndex == 1){
        
        //相册
        [self photoShop];
    }
    
    
}
//相册
- (void)photoShop{
    
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    //设置相册的类型
    //所有同步到iPhone的图像以及包括⽤用户拍摄的图⽚片在内的任何相册
    pick.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
   
    pick.delegate = self;
    
    [self.viewController presentViewController:pick animated:YES completion:nil];
    
}
//拍照
- (void)photoPai{
    //判断后摄像头是否能用
    BOOL isAvailabe = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    //允许⽤用户使⽤用iPhone内置的摄像头的拍照
    pick.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (isAvailabe) {
        pick.sourceType = UIImagePickerControllerSourceTypeCamera;
        pick.delegate = self;
        
        [[self viewController] presentViewController:pick animated:YES completion:nil];
    }
    //如果来自照相机的图片，可以通过一下方法保存到相册
    
    
}

@end
